package com.xx.doublexchat.common.user.service.impl;

import com.xx.doublexchat.common.common.constant.BaseConstant;
import com.xx.doublexchat.common.common.constant.RedisKey;
import com.xx.doublexchat.common.common.utils.JwtUtils;
import com.xx.doublexchat.common.common.utils.RedisUtils;
import com.xx.doublexchat.common.user.service.ILoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {
    //token存储时间
    public static final int TOKEN_EXPIRE_DAYS = 3;
    //token更新时间
    public static final int TOKEN_RENEWAL_DAYS = 1;

    @Autowired
    private JwtUtils jwtUtils;

    ThreadPoolExecutor executor; //线程池

    /**
     * 异步刷新Token
     * @param token
     */
    @Override
    @Async
    public void renewalTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        if (null == uid) {
            return;
        }
        //获取tokenKey
        String userTokenKey = getUserTokenKey(uid);
        Long expireDays = RedisUtils.getExpire(userTokenKey, TimeUnit.DAYS);
        //如果小于0表示不存在的key
        if (expireDays < BaseConstant.ZERO) {
            return;
        }

        //小于1天的KEY续期
        if (expireDays < TOKEN_RENEWAL_DAYS) {
            RedisUtils.expire(userTokenKey,TOKEN_EXPIRE_DAYS,TimeUnit.DAYS);
        }
    }

    @Override
    public String login(Long id) {
        //获取Token
        String token = jwtUtils.createToken(id);
        RedisUtils.set(getUserTokenKey(id), token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        Long uid = jwtUtils.getUidOrNull(token);
        if (Objects.isNull(uid)) {
            return null;
        }
        String oldToken = RedisUtils.getStr(getUserTokenKey(uid));
        if (StringUtils.isBlank(oldToken)) {
            return null;
        }
        return Objects.equals(oldToken, token) ? uid : null;
    }

    /**
     * 获取token
     * @param uid
     * @return
     */
    private String getUserTokenKey(Long uid) {
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING, uid);
    }
}
